package com.sy.simpleegg.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.sy.simpleegg.R
import com.sy.simpleegg.adapter.SupplementOrderAdapter
import com.sy.simpleegg.base.BaseMvpFragment
import com.sy.simpleegg.bean.SupplementOrderBean
import com.sy.simpleegg.databinding.FragmentSupplementBinding
import com.sy.simpleegg.event.SupplementCoinsEvent
import com.sy.simpleegg.event.SupplementCoinsFinishEvent
import com.sy.simpleegg.event.SupplementEvent
import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.ext.setDeviceStatus
import com.sy.simpleegg.ext.showToastMsg
import com.sy.simpleegg.mvp.contract.SupplementContract
import com.sy.simpleegg.mvp.presenter.SupplementPresenter
import com.sy.simpleegg.util.DateTimeUtil
import com.sy.simpleegg.util.GsonUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class SupplementFragment :
    BaseMvpFragment<SupplementContract.View, SupplementContract.Presenter, FragmentSupplementBinding>(),
    SupplementContract.View {

    private var supplementOrderList: MutableList<SupplementOrderBean> = mutableListOf()
    private var adapter: SupplementOrderAdapter? = null
    private var outing = false//是否出币中
    private var outPosition = -1//本次出币列表的position
    private var outQuantity = -1L//本次需要出币数
    private var outFlag = ""//本次出币标记（控制板出币订单号）
    private var outJob: Job? = null
    private var currentRemain = 0L//当前实时剩余币数
    private var lastRemain = 0L//上一次记录的剩余币数
    private var count = 0//出币计时，有出币信息返回就重置为0

    companion object {
        fun getInstance(): SupplementFragment = SupplementFragment()
    }

    override fun createPresenter(): SupplementContract.Presenter = SupplementPresenter(lifecycleScope)

    override fun attachLayoutRes(): Int = R.layout.fragment_supplement

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        openEventBus = true
        isCountDownBackHome = false
    }

    override fun initView(view: View) {
        super.initView(view)

    }

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
    ): FragmentSupplementBinding {
        return FragmentSupplementBinding.inflate(inflater, container, false)
    }

    override fun lazyLoad() {
        getSupplementOrder()
    }

    override fun onResume() {
        super.onResume()
        logFile("${javaClass.simpleName} onResume")
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden) {
            logFile("${javaClass.simpleName}隐藏")
        } else {
            logFile("${javaClass.simpleName}显示")
        }
    }

    override fun loadData(datas: MutableList<SupplementOrderBean>) {
        supplementOrderList = datas
        if (adapter == null){
            binding.rvErrOrders.layoutManager = LinearLayoutManager(context)
            adapter = SupplementOrderAdapter(supplementOrderList, object : SupplementOrderAdapter.OnOutClickListener{
                override fun onOutCoins(id: Long, position: Int, flag: String, outQuantity: Long) {
                    handleOutCoins(id, position, flag, outQuantity)
                }
            })
            binding.rvErrOrders.adapter = adapter
        }else{
            logFile("刷新异常订单列表：${GsonUtil.getInstance()?.toJson(supplementOrderList)}")
            adapter?.refreshData(supplementOrderList?: mutableListOf())
        }
    }


    override fun showLoading() {

    }

    override fun hideLoading() {

    }

    private fun getSupplementOrder(){
        val endDate = DateTimeUtil.nowDate
        val startDate = DateTimeUtil.getDaysAgoDate(7)
        mPresenter?.getOrder(startDate, endDate)
    }

    private fun handleOutCoins(id: Long, position: Int, uuid: String, quantity: Long){
        if (outing){
            showToastMsg(getString(R.string.outing))
            return
        }
        if (quantity <= 0){
            showToastMsg(getString(R.string.out_complete))
        }
        outing = true
        outPosition = position
        outQuantity = quantity
        outFlag = uuid
        outJob?.cancel()

        outJob = lifecycleScope.launch {
            logFile("出币异常订单补币：开始")
            cancelCountDown()
            val orderId = id
            val timeout = 15*1000
            val interval = 500L
            val overCount = timeout/interval
            count = 0
            currentRemain = outQuantity
            lastRemain = outQuantity

            sendOutCmd(outFlag, outQuantity)
            do {
                delay(interval)
                count ++

                if (lastRemain != currentRemain){
                    lastRemain = currentRemain
                    //刷新页面数据
                    if (supplementOrderList.isEmpty()){

                    }else{
                        supplementOrderList[outPosition].let {
                            val realCoins = (it.orderCoins.toLong() - lastRemain).toString()
                            it.realCoins = realCoins
                            mPresenter?.setRealAmount(orderId, realCoins)
                            withContext(Dispatchers.Main){
                                logFile("刷新item position=$outPosition realCoins=$realCoins ${GsonUtil.getInstance()?.toJson(it)}")
                                adapter?.notifyItemChanged(outPosition, it)
                            }
                        }

                    }
                }

            }while (count < overCount && lastRemain > 0)

            if (lastRemain > 0){
                showToastMsg(getString(R.string.out_coins_finish_err))
                setDeviceStatus(false)
            }else{
                setDeviceStatus(true)
            }

            delay(1000)

            //重新加载数据
            withContext(Dispatchers.Main){
                getSupplementOrder()
            }

            delay(1000)
            logFile("出币异常订单补币：结束")
            outing = false
            EventBus.getDefault().post(SupplementCoinsFinishEvent(0))
        }
    }

    private fun sendOutCmd(flag: String, quantity: Long){
        EventBus.getDefault().post(SupplementCoinsEvent(flag, quantity))
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun supplementEvent(event: SupplementEvent) {
        logFile("出币异常订单补币刷新事件：${GsonUtil.getInstance()!!.toJson(event)}")
        if (!outing) return

        count = 0
        currentRemain = event.remainCoins.toLong()
    }

}